package com.niuwa.quartz.schedule;

import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import com.niuwa.quartz.entity.JobEntity;
import com.niuwa.quartz.service.JobService;

public abstract class AbstractEdiJob implements Job {

	protected JobEntity jobEntity;
	private static Logger logger = Logger.getLogger(AbstractEdiJob.class);
	private Long beginTime;
	private Boolean runStatus = true;

	@Override
	public void execute(JobExecutionContext context)
			throws JobExecutionException {
//		JobService jobService = SchedulerHelper.getJobService(context);
//		preExcute(jobService, context);
//		runStatus = exeucuteInternal(context);
//		postExcute(jobService, context);
	}

	abstract public boolean exeucuteInternal(JobExecutionContext context);

	public void preExcute(JobService jobService, JobExecutionContext context) {
		beginTime = System.currentTimeMillis();
	}

	public void postExcute(JobService jobService, JobExecutionContext context) {
		// 获得最新的jobEntiry
		jobEntity = jobService.getJobById(jobEntity.getJobId());
		if (jobEntity == null) {
			logger.warn(jobEntity.getJobId() + "job不能存在");
			return;
		}
		if (context.getFireTime() != null)
			jobEntity.setRuntimeLast(context.getFireTime());
		if (context.getNextFireTime() != null)
			jobEntity.setRuntimeNext(context.getNextFireTime());
		if (runStatus) {
			jobEntity.setJobStatus(jobEntity.STATUS_FINISHED);
		} else {
			jobEntity.setJobStatus(jobEntity.STATUS_EXCEPTION);
			jobEntity.setExceptionTimes(jobEntity.getExceptionTimes() + 1);
		}
		Long times = jobEntity.getRunTimes();
		jobEntity.setRunTimes((times == null ? 0l : times) + 1);
		Long duration = jobEntity.getRunDuration();
		jobEntity.setRunDuration((duration == null ? 0l : duration)
				+ (System.currentTimeMillis() - beginTime));
		jobService.updateJob(jobEntity);
		// jobEntity这里的改变不能改变JobDetail里的JobEntity，因为生产的job是JobDetail的JobEntity的复制
	}

	public void setJobEntity(JobEntity jobEntity) {
		this.jobEntity = jobEntity;
	}
}
